'use client';
import Link from 'next/link';
import { useState, createContext, useContext } from 'react';

// 创建加载状态上下文
interface LoadingContextType {
  isLoading: boolean;
  setIsLoading: (loading: boolean) => void;
}

export const LoadingContext = createContext<LoadingContextType | undefined>(undefined);

// 自定义Link组件，点击时立即显示加载状态
interface CustomLinkProps {
  href: string;
  children: React.ReactNode;
  className?: string;
  onClick?: () => void;
}

export const CustomLink = ({ href, children, className, onClick }: CustomLinkProps) => {
  const loadingContext = useContext(LoadingContext);
  
  if (!loadingContext) {
    throw new Error('CustomLink must be used within a LoadingProvider');
  }

  const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
    // 立即显示加载状态
    loadingContext.setIsLoading(true);
    
    // 如果有自定义onClick函数，调用它
    if (onClick) {
      onClick();
    }
  };

  return (
    <Link
      href={href}
      className={className}
      onClick={handleClick}
    >
      {children}
    </Link>
  );
};

// 加载状态提供者组件
interface LoadingProviderProps {
  children: React.ReactNode;
}

export const LoadingProvider = ({ children }: LoadingProviderProps) => {
  const [isLoading, setIsLoading] = useState(false);

  return (
    <LoadingContext.Provider value={{ isLoading, setIsLoading }}>
      {children}
    </LoadingContext.Provider>
  );
};
